package com.itheima.wisdomnext.mapper;

import com.itheima.wisdomnext.entity.Users;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    // 根据用户名查找用户
    @Select("SELECT * FROM users WHERE username = #{username} AND banned != 1")
    Users findByUsername(@Param("username") String username);

    // 检查用户名是否已存在
    @Select("SELECT COUNT(1) > 0 FROM users WHERE username = #{username} AND banned != 1")
    boolean existsByUsername(@Param("username") String username);

    // 插入新用户
    @Insert("INSERT INTO users (userid, username, password, avatar, address, phone, nickname) " +
            "VALUES (#{userId}, #{username}, #{password}, #{avatar}, #{address}, #{phone}, #{nickname})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(Users user);

    @Update("<script>" +
            "UPDATE users SET " +
            "<choose>" +
            "<when test='nickname != null'>nickname = #{nickname}</when>" +
            "<otherwise></otherwise>" +
            "</choose>" +
            "<choose>" +
            "<when test='phone != null'>phone = #{phone}</when>" +
            "<otherwise></otherwise>" +
            "</choose>" +
            "<choose>" +
            "<when test='address != null'>address = #{address}</when>" +
            "<otherwise></otherwise>" +
            "</choose>" +
            "WHERE userid = #{userId}" +
            "</script>")
    int updateUserInfo(Users users);

    // 根据 userId 查询用户信息
    @Select("SELECT * FROM users WHERE userid = #{userId}")
    Users getUserById(int userId);

    // 根据 userId 查询用户信息
    @Select("SELECT * FROM users WHERE userid = #{userId}")
    List<Users> getUserByIdPost(int userId);

    // 更新用户头像路径
    @Update("UPDATE users SET avatar = #{avatar} WHERE userid = #{userId}")
    int updateAvatar(int userId, String avatar);

    // 查询用户关注的人
    @Select("SELECT followed_id FROM follows WHERE follower_id = #{userId}")
    List<Integer> getFollowedUserIds(@Param("userId") int userId);

    @Select("SELECT * FROM users")
    List<Users> findAllUsers();
}
